<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{common/header :: commonHead}"></head>
<META HTTP-EQUIV="Cache-Control" CONTENT= "no-cache, must-revalidate">
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight" th:with="page=${pageObj.page},size=${pageObj.pageSize},total=${pageObj.total},totalPage=${pageObj.totalPage},keyword=${pageObj.keyword},fromDate=${pageObj.fromDate},toDate=${pageObj.toDate}">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>用户分组</h5>
                    <div class="ibox-tools">
                        <a href="javascript: void(0);" class="modal-trigger" data-toggle="modal" data-target="#addGroup" title="添加分组"><i class="glyphicon glyphicon-plus-sign"></i></a>
                        <a href="javascript: window.location.href='/user_group/list';" title="刷新"><i
                                class="glyphicon glyphicon-repeat"></i></a>
                    </div>
                </div>
                <div class="ibox-content">
                    <div class="">
                    </div>
                    <div id="editable_wrapper" class="dataTables_wrapper form-inline" role="grid">
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="dataTables_length" id="editable_length"><label>每页
                                <select name="editable_length" aria-controls="editable" class="form-control input-sm" id="page_size_selector">
                                    <option th:selected="${size eq 5}" value="5">5</option>
                                    <option th:selected="${size eq 10}" value="10">10</option>
                                    <option th:selected="${size eq 25}" value="25">25</option>
                                    <option th:selected="${size eq 50}" value="50">50</option>
                                    <option th:selected="${size eq 100}" value="100">100</option>
                                </select> 条记录</label>
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="input-daterange input-group" id="datepicker">
                                    <input type="text" class="input-sm form-control" name="start" id="start_date" placeholder="开始时间" th:value="${pageObj.fromDate}">
                                    <span class="input-group-addon">到</span>
                                    <input type="text" class="input-sm form-control" name="end" id="end_date" placeholder="结束时间" th:value="${pageObj.toDate}">
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="input-group" style="float: right">
                                    <input th:value="${pageObj.keyword}" type="text" placeholder="请输入关键词" class="input-sm form-control" id="search_bar">
                                    <span class="input-group-btn">
                                        <button type="button" class="btn btn-sm btn-primary" id="search-btn"> 搜索</button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="datepicker datepicker-dropdown dropdown-menu datepicker-orient-left datepicker-orient-bottom" style="display: none; top: 901.2px; left: 264.8px; z-index: 10;"><div class="datepicker-days" style="display: block;"><table class=" table-condensed"><thead><tr><th class="prev" style="visibility: visible;">«</th><th colspan="5" class="datepicker-switch">十一月 2014</th><th class="next" style="visibility: visible;">»</th></tr><tr><th class="dow">日</th><th class="dow">一</th><th class="dow">二</th><th class="dow">三</th><th class="dow">四</th><th class="dow">五</th><th class="dow">六</th></tr></thead><tbody><tr><td class="old day">26</td><td class="old day">27</td><td class="old day">28</td><td class="old day">29</td><td class="old day">30</td><td class="old day">31</td><td class="day">1</td></tr><tr><td class="day">2</td><td class="day">3</td><td class="day">4</td><td class="day">5</td><td class="day">6</td><td class="day">7</td><td class="day">8</td></tr><tr><td class="day">9</td><td class="day">10</td><td class="selected day">11</td><td class="range day">12</td><td class="range day">13</td><td class="range day">14</td><td class="range day">15</td></tr><tr><td class="range day">16</td><td class="active selected day">17</td><td class="day">18</td><td class="day">19</td><td class="day">20</td><td class="day">21</td><td class="day">22</td></tr><tr><td class="day">23</td><td class="day">24</td><td class="day">25</td><td class="day">26</td><td class="day">27</td><td class="day">28</td><td class="day">29</td></tr><tr><td class="day">30</td><td class="new day">1</td><td class="new day">2</td><td class="new day">3</td><td class="new day">4</td><td class="new day">5</td><td class="new day">6</td></tr></tbody><tfoot><tr><th colspan="7" class="today" style="display: none;">今天</th></tr><tr><th colspan="7" class="clear" style="display: none;">清空</th></tr></tfoot></table></div><div class="datepicker-months" style="display: none;"><table class="table-condensed"><thead><tr><th class="prev" style="visibility: visible;">«</th><th colspan="5" class="datepicker-switch">2014</th><th class="next" style="visibility: visible;">»</th></tr></thead><tbody><tr><td colspan="7"><span class="month">1</span><span class="month">2</span><span class="month">3</span><span class="month">4</span><span class="month">5</span><span class="month">6</span><span class="month">7</span><span class="month">8</span><span class="month">9</span><span class="month">10</span><span class="month active">11</span><span class="month">12</span></td></tr></tbody><tfoot><tr><th colspan="7" class="today" style="display: none;">今天</th></tr><tr><th colspan="7" class="clear" style="display: none;">清空</th></tr></tfoot></table></div><div class="datepicker-years" style="display: none;"><table class="table-condensed"><thead><tr><th class="prev" style="visibility: visible;">«</th><th colspan="5" class="datepicker-switch">2010-2019</th><th class="next" style="visibility: visible;">»</th></tr></thead><tbody><tr><td colspan="7"><span class="year old">2009</span><span class="year">2010</span><span class="year">2011</span><span class="year">2012</span><span class="year">2013</span><span class="year active">2014</span><span class="year">2015</span><span class="year">2016</span><span class="year">2017</span><span class="year">2018</span><span class="year">2019</span><span class="year new">2020</span></td></tr></tbody><tfoot><tr><th colspan="7" class="today" style="display: none;">今天</th></tr><tr><th colspan="7" class="clear" style="display: none;">清空</th></tr></tfoot></table></div></div>
                        <table class="table table-striped table-bordered table-hover  dataTable" id="editable"
                               aria-describedby="editable_info">
                            <thead>
                                <tr role="row">
                                    <th aria-label="分组名称" style="width: 20%;" >分组名称</th>
                                    <th aria-label="简介" style="width: 30%;">简介</th>
                                    <th aria-label="创建时间" style="width: 25%;">创建时间</th>
                                    <th aria-label="操作" style="width: 25%;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="gradeA odd" th:if="${#lists.isEmpty(pageObj.list)}">
                                    <td colspan="4" style="text-align: center">
                                        没有数据o&gt;^&lt;o
                                    </td>
                                </tr>
                                <tr class="gradeA odd" th:each="item : ${pageObj.list}">
                                    <td th:with="keyword=${pageObj.keyword},name=${item.groupName}" th:utext="${null == keyword ? name : #strings.replace(name,keyword,'<span style= &quot;color: red;font-weight:bold&quot;>'+ keyword +'</span>')}"></td>
                                    <td th:with="keyword=${pageObj.keyword},desc=${item.groupInfo}" th:utext="${null == keyword ? desc : #strings.replace(desc,keyword,'<span style= &quot;color: red;font-weight:bold&quot;>'+ keyword +'</span>')}"></td>
                                    <td th:text="${item.createTime}"></td>
                                    <td class="center">
                                        <a type="button" th:onclick="ticketPush([[${item.id}]],[[${item.groupName}]])" class="modal-trigger" data-toggle="modal" data-target="#ticketModel" title="推送优惠券"><i class="fa fa-ticket"></i></a>
                                        <a type="button" th:onclick="deleteItem([[${item.id}]])" title="删除分组"><i class="fa fa-trash"></i></a>
                                        <a type="button" th:onclick="setGroupId([[${item.id}]],[[${item.groupName}]])" class="modal-trigger" data-toggle="modal" data-target="#addUser" title="添加用户"><i class="fa fa-user-plus"></i></a>
                                        <a type="button" th:onclick="loadUserTable([[${item.id}]],[[${item.groupName}]])" class="modal-trigger" data-toggle="modal" data-target="#checkGroup" title="查看分组用户"><i class="glyphicon glyphicon-eye-open"></i></a>
                                        <a type="button" th:onclick="loadHref([[${item.id}]])" title="导出数据"><i class="glyphicon glyphicon-export"></i></a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <div class="row">
                            <div class="col-sm-6" th:with="page=${pageObj.page},size=${pageObj.pageSize},total=${pageObj.total},totalPage=${pageObj.totalPage}">
                                <div class="dataTables_info" role="alert" aria-live="polite" aria-relevant="all"
                                     th:text="${'显示 '+(page*size+1)+' 到 '+((page+1) lt totalPage ? (size + page * size) : (total % size == 0 ? total : (total % size + size * page))) + ' 项，共 ' + total + ' 项'}">
                                </div>
                            </div>
                            <div class="col-sm-6" th:with="page=${pageObj.page},size=${pageObj.pageSize},total=${pageObj.total},totalPage=${pageObj.totalPage}">
                                <div class="dataTables_paginate paging_simple_numbers">
                                    <ul class="pagination" th:if="${totalPage>1}">
                                        <li th:class="${page==0}?'paginate_button previous disabled':'paginate_button previous'">
                                            <a th:href="${(page==0)?'#':'/user_group/list?page='+page
                                             +'&pageSize='+size
                                             +'&keyword='+(null==keyword?'':keyword)
                                             +'&fromDate='+(null==fromDate?'':fromDate)
                                             +'&toDate='+(null==toDate?'':toDate)}">上一页</a>
                                        </li>
                                        <li th:if="${totalPage<10}" th:each="i:${#numbers.sequence(1,totalPage)}"
                                            th:class="${i==page+1?'active':''}">
                                            <a th:href="${'/user_group/list?page='+i
                                            +'&pageSize='+size
                                            +'&keyword='+ (null==keyword?'':keyword)
                                            +'&fromDate='+(null==fromDate?'':fromDate)
                                            +'&toDate='+(null==toDate?'':toDate)}"
                                               th:text="${i}"></a>
                                        </li>
                                        <li th:if="${page<4&&totalPage>=9}" th:each="i:${#numbers.sequence(1,9)}"
                                            th:class="${i==page+1?'active':''}">
                                            <a th:href="${'/user_group/list?page='+i
                                            +'&pageSize='+size
                                            +'&keyword='+ (null==keyword?'':keyword)
                                            +'&fromDate='+(null==fromDate?'':fromDate)
                                            +'&toDate='+(null==toDate?'':toDate)}"
                                               th:text="${i}"></a>
                                        </li>
                                        <li th:if="${page>=4&&totalPage>=9&&page+5<totalPage}" th:each="i:${#numbers.sequence(page - 3,page + 5)}"
                                            th:class="${i==page+1?'active':''}">
                                            <a th:href="${'/user_group/list?page='+i
                                            +'&pageSize='+size
                                            +'&keyword='+ (null==keyword?'':keyword)
                                            +'&fromDate='+(null==fromDate?'':fromDate)
                                            +'&toDate='+(null==toDate?'':toDate)}"
                                               th:text="${i}"></a>
                                        </li>
                                        <li th:if="${page>=4&&totalPage>=9&&page+5>=totalPage}" th:each="i:${#numbers.sequence(totalPage - 8,totalPage)}"
                                            th:class="${i==page+1?'active':''}">
                                            <a th:href="${'/user_group/list?page='+i
                                            +'&pageSize='+size
                                            +'&keyword='+ (null==keyword?'':keyword)
                                            +'&fromDate='+(null==fromDate?'':fromDate)
                                            +'&toDate='+(null==toDate?'':toDate)}"
                                               th:text="${i}"></a>
                                        </li>
                                        <li th:class="${page+1==totalPage||totalPage<1}?'paginate_button next disabled':'paginate_button next'" >
                                            <a th:href="${(page+1==totalPage||totalPage<1) ? '#' : '/user_group/list?page='+(page+2)
                                             +'&pageSize='+size
                                             +'&keyword='+(null==keyword?'':keyword)
                                             +'&fromDate='+(null==fromDate?'':fromDate)
                                             +'&toDate='+(null==toDate?'':toDate)}">下一页</a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade in" id="checkGroup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 800px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="checkUserGroup">查看用户</h4>
            </div>
            <div class="modal-body" style="height: 500px">
                <div class="input-group" style="width: 100%"></div>
                <div id="check_user_table"></div>
            </div>
        </div>

    </div>
</div>
<div class="modal fade in" id="addGroup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 400px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="userModalLabel">创建分组</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="create_form" method="post" action="/user_group/add">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">名称：</label>
                        <div class="col-sm-9">
                            <input placeholder="请输入分组名称" name="groupName" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">描述：</label>
                        <div class="col-sm-9">
                            <textarea placeholder="请输入分组简述" name="groupInfo" class="form-control"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="submit_create">提交</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade in" id="addUser" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 800px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">添加用户</h4>
            </div>
            <div class="modal-body" style="height: 500px">
                <div class="input-group" style="width: 100%">
                    <div class="row">
                        <div class="form-group col-sm-6">
                            <label class="col-sm-4 control-label">注册时间：</label>
                            <div class="input-daterange input-group col-sm-8">
                                <input type="text" class="input-sm form-control" id="register_start_date" name="fromDate"  autocomplete="off" placeholder="开始时间" th:value="${pageObj.fromDate}">
                                <span class="input-group-addon">到</span>
                                <input type="text" class="input-sm form-control" id="register_end_date" name="toDate" autocomplete="off" placeholder="结束时间" th:value="${pageObj.toDate}">
                            </div>
                        </div>
                        <div class="form-group col-sm-6">
                            <label class="col-sm-4 control-label">用户积分：</label>
                            <div class="input-daterange input-group col-sm-8">
                                <input type="text" class="input-sm form-control" id="from_int" name="fromInt" autocomplete="off" placeholder="最小值">
                                <span class="input-group-addon">~</span>
                                <input type="text" class="input-sm form-control" id="to_int" name="toInt" autocomplete="off" placeholder="最大值">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-sm-6">
                            <label class="col-sm-4 control-label">生日：</label>
                            <div class="input-daterange input-group col-sm-8">
                                <input type="text" class="input-sm form-control" id="birthday_start" name="birthday_start" autocomplete="off" placeholder="开始时间">
                                <span class="input-group-addon">到</span>
                                <input type="text" class="input-sm form-control" id="birthday_end" name="birthday_end" autocomplete="off" placeholder="结束时间">
                            </div>
                        </div>
                        <div class="form-group col-sm-4">
                            <label class="col-sm-4 control-label">性别：</label>
                            <div class="radio radio-info radio-inline">
                                <input type="radio" id="inlineRadio1" onclick="$(this).attr('checked','checked');$('#inlineRadio2').removeAttr('checked')" name="gender" value="0">
                                <label for="inlineRadio1">男</label>
                            </div>
                            <div class="radio radio-danger radio-inline">
                                <input type="radio" id="inlineRadio2" onclick="$(this).attr('checked','checked');$('#inlineRadio1').removeAttr('checked')" name="gender" value="1">
                                <label for="inlineRadio2">女</label>
                            </div>
                        </div>
                        <div class="form-group col-sm-2" style="margin-top: 8px;">
                            <button class="btn btn-info btn-xs" id="user-filter" title="过滤" type="button"><i class="fa fa-filter"></i>过滤</button>
                            <button class="btn btn-warning btn-xs" id="clean-filter" title="清空" type="button"><i class="fa fa-times"></i>清空</button>
                        </div>
                    </div>
                </div>
                <div class="input-group">
                    <div id="user-group-search">
                        <input type="text" placeholder="请输入关键词" class="input-sm form-control" id="search_bar_user" style="width: 200px;">
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-sm btn-primary" id="search_btn_user"> 搜索</button>
                        </span>
                    </div>
                </div>
                <div id="user_table"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="submit-table">提交</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade in" id="ticketModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="width: 500px">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="ticketModelLabel"></h4>
            </div>
            <div class="modal-body" style="height: 320px">
                <div class="input-group">
                    <input value="" type="text" placeholder="输入关键词" class="input-sm form-control" id="search-ticket">
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-sm btn-primary" id="search-ticket-btn"> 搜索</button>
                    </span>
                </div>
                <table class="table">
                    <thead style="display:table;width:100%;table-layout:fixed;">
                    <tr>
                        <th style="width: 20%;">LOGO</th>
                        <th style="width: 35%;">券名称</th>
                        <th style="width: 10%;">总量</th>
                        <th style="width: 15%;">类型</th>
                        <th style="width: 20%;">操作</th>
                    </tr>
                    </thead>
                    <tbody style="display:block;height:200px;overflow-y:auto;width: 100%;" id="inner">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script th:inline="javascript">

    let pushGroupId = '';
    function ticketPush(id,name) {
        if (null == name) {
            name = '未命名';
        }
        pushGroupId = '"' + id + '"';
        $("#ticketModelLabel").html("券推送给用户组[" + name + "]");
        setData();
    }
    function setData() {
        $("#inner").html('');
        let _this = $("#search-ticket");
        let keyword = _this.val();
        layer.load(1);
        setTimeout(function () {
            $.ajax({
                url:"/coupon/search?keyword=" + keyword + "&activeId=",
                type:"get",
                success: function (res) {
                    let list = res.data.list;
                    layer.closeAll('loading');
                    if (null == list) {
                        return;
                    }
                    let str = '';
                    list.forEach(obj => {
                        let objId = '"' + obj.id + '"';
                    str += "<tr style='display:table;width:100%;table-layout:fixed;'>" +
                        "<td style='display:none;'>" +obj.id + "</td>" +
                        "<td style='width: 20%'><img style='height: 40px' src='" + obj.image + "' onerror=\"this.src='/img/default_coup.png'\"></td>" +
                        "<td style='width: 35%'>" + obj.name + "</td>" +
                        "<td style='width: 10%'>" + (obj.sumTatal == null ? '∞' : obj.remainTotal) + "</td>" +
                        "<td style='width: 15%'>" + (obj.type == 1 ? '优惠券' : '停车券') + "</td>" +
                        "<td style='width: 20%'><a type='button' href='javascript:pushCoupon(" + pushGroupId + "," + objId +");' class='btn btn-primary btn-xs'>推送</a></td>" +
                        "</tr>"
                });
                    $("#inner").html(str);
                },
                error : function () {
                    layer.closeAll('loading');
                }
            });
        },500);
    }
    $("#search-ticket-btn").click(function () {
        setData();
    });
    $("#search-ticket").on("keydown",function (e) {
        if (e.keyCode != 13) {
            return;
        }
        setData();
    });
    function pushCoupon(groupId, coupId) {
        let num = prompt("请输入优惠券数量","1");
        while (isNaN(num) && null != num) {
            // layer.msg('请输入正确的数字',{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
            num = prompt("请输入正确的数字","1");
        }
        if (null == num) {
            return;
        }
        let coupIds = [];
        coupIds.push(coupId)
        let postData = {groupId:groupId,couponIds:coupIds,couponNum:num};
        $.ajax({
            url:"/user_group/pushCoupon",
            data:JSON.stringify(postData),
            contentType: 'application/json',
            type:"POST",
            success: function (data) {
                let code = data.resCode;
                if(code == 0) {
                    layer.alert("发券成功");
                    setData();
                }
                else {
                    layer.alert(data.resMsg);
                }
            }
        });
    }


    let ids =new Array();
    let filterData = {
        fromDate : '',
        toDate : '',
        keyword : '',
        gender : '',
        fromInt : null,
        toInt : null,
        birthdayFrom: '',
        birthdayTo: ''
    }

    $("#user-filter").click(function () {
        filterData.fromDate = $("#register_start_date").val();
        filterData.toDate = $("#register_end_date").val();
        filterData.gender = $("input[name='gender']:checked").val();
        filterData.fromInt = $("#from_int").val();
        filterData.toInt = $("#to_int").val();
        filterData.birthdayFrom = $("#birthday_start").val();
        filterData.birthdayTo = $("#birthday_end").val();
        reloadTable();
    });
    /**
     *  设置分组Id
     */
    let groupId = '';
    let currentData = [];
    function setGroupId(id,name) {
        groupId = id;
        $("#myModalLabel").html('添加用户至分组：' + name);
        if (!groupId == '') {
            $.ajax({
                url: '/user_group/getUserByGroupId',
                type: 'POST',
                contentType:'application/json',
                data: JSON.stringify({groupId: groupId}),
                success: function(res) {if (res.resCode == 0) {ids = res.data;}loadTable();}
            });
        }
    }
    /**
     *  向分组中添加用户
     */
    let table = '';
    let keyword = '';
    let page = null;
    let size = null;
    $("#search_bar_user").val(keyword);
    $("#search_btn_user").click(function(){
        keyword = $("#search_bar_user").val();
        reloadTable(page,size);
    });
    $("#clean-filter").click(function () {
        $("#register_start_date").val(null);
        $("#register_end_date").val(null);
        $("input[name='gender']:checked").removeAttr('checked');
        $("#from_int").val(null);
        $("#to_int").val(null);
        $("#birthday_start").val(null);
        $("#birthday_end").val(null);
        filterData.fromDate = ''
        filterData.toDate = ''
        filterData.gender = null
        filterData.fromInt = null
        filterData.toInt = null
        filterData.birthdayFrom = ''
        filterData.birthdayTo = ''
        keyword = ''
        reloadTable(page, size);
    });
    function reloadTable(page,size) {
        table.reload(
            'user_table',
            {
                where: {
                    'keyword':keyword,
                    'fromDate':filterData.fromDate,
                    'toDate':filterData.toDate,
                    'gender':filterData.gender,
                    'fromInt':filterData.fromInt,
                    'toInt':filterData.toInt,
                    'birthdayFrom':filterData.birthdayFrom,
                    'birthdayTo':filterData.birthdayTo,
                    'page':page,
                    'size':size
                }
            }
        );
    }
    function loadTable() {
        layui.use('table', function(){
            table = layui.table;
            table.render({
                id: 'user_table',
                elem: '#user_table',
                height: 330,
                url: '/user/table_list',
                method: 'post',
                size: 'sm',
                limits:[10,20,40,100],
                request: {
                    pageName: 'page',
                    limitName: 'size'
                },
                response: {
                    statusName: 'status', //规定数据状态的字段名称，默认：code
                    statusCode: 200, //规定成功的状态码，默认：0
                    msgName: 'msg', //规定状态信息的字段名称，默认：msg
                    countName: 'total', //规定数据总数的字段名称，默认：count
                    dataName: 'rows' //规定数据列表的字段名称，默认：data
                },
                page: true,
                cols: [[ //表头
                    {type: 'checkbox', width : 50 , fixed:'left'},
                    {field: 'memberName', title: '用户名', width:120, sort: true, fixed: 'left'},
                    {field: 'name', title: '姓名', width:80, sort: true, fixed: 'left'},
                    {field: 'memberCardNum', title: '卡号', sort: true, width:100,fixed:'left'},
                    {field: 'phone', title: '手机号', width:110, sort: true,fixed:'left'},
                    {field: 'integral', title: '积分', width:80},
                    {field: 'createTime', title: '创建时间', sort: true,width: 150},
                    {field: 'birthday', title: '生日', sort: true,width: 100},
                    {field: 'gender', templet:function (e) {return e.gender==0?'男':'女'},title: '性别', width: 60}
                ]],
                done: function(res, curr, count){
                    page = curr;
                    size = res.size;
                    currentData = [];
                    buttonClickable();
                    for(let i=0;i< res.rows.length;i++){
                        currentData.push(res.rows[i].id);
                        for (let j = 0; j < ids.length; j++) {
                            if(res.rows[i].id == ids[j]) {
                                res.rows[i]["LAY_CHECKED"]='true';
                                let index= res.rows[i]['LAY_TABLE_INDEX'];
                                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                        }
                    }

                    let checkStatus = table.checkStatus('user_table');
                    if(checkStatus.isAll){
                        $('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }

                }
            });
            table.on('checkbox', function(obj){
                if (obj.type == 'one') {
                    if (!obj.checked && ids != null) {
                        ids.remove(obj.data.id);
                    }
                    if (obj.checked && ids != null) {
                        ids.push(obj.data.id);
                    }
                }
                let checkStatus = table.checkStatus('user_table');
                if ('all' == obj.type && obj.checked) {
                    if (obj.checked && ids != null) {
                        checkStatus.data.forEach((e) => {
                            ids.push(e.id);
                    });
                    }
                    if (!obj.checked && ids != null) {
                        for (let i = 0; i < ids.length; i++) {
                            for (let j = 0; j < currentData.length; j++) {
                                if (ids[i] == currentData[j]) {
                                    ids.remove(ids[i]);
                                }
                            }
                        }
                    }
                }
                console.log(ids)
            });
        });
    }
    Array.prototype.indexOf = function(val) {
        for (let i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };
    Array.prototype.remove = function(val) {
        let index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
    /**
     *  提交分组会员Id
     */

    $("#submit-table").click(() => {
        $.ajax({
            url: "/user_group/addUser",
            type: "POST",
            contentType:'application/json',
            data: JSON.stringify({groupId:groupId,userIds:ids}),
            success: function (res) {
                if (res.resCode == 0) {
                    layer.msg('添加用户成功',{icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                    $('#addUser').modal('hide');
                } else {
                    layer.msg('添加用户失败',{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
                }
            }
        });
    });

    /**
     *  删除分组
     */
    function deleteItem(id) {
        $.ajax({
            url: '/user_group/delete?id='+id,
            type: "GET",
            success: function (res) {
                if (res.resCode == 0) {
                    layer.msg('删除成功',{icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                    window.location.reload();
                } else {
                    layer.msg('删除失败',{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
                }
            },
            error: function (res) {
                layer.msg('删除失败，请重试',{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
            }
        });
    }

    /**
     * 提交添加分组
     */
    $("#submit_create").click(() => {
        try {
            $("#create_form").ajaxSubmit(data => {
        if (data.resCode == 0) {
        layer.msg("创建成功",{icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
        window.location.href = '/user_group/list';
    } else {
        layer.msg(data.resMsg,{icon: 15,time: 1000,shade : [0.5 , '#000' , true]})
    }
    });
    } catch (e) {
        layer.alert('系统异常')
    }

    });

    function loadUserTable(id,name) {
        let groupId = id;
        $("#checkUserGroup").html('查看 '+name+' 组内用户');
        layui.use('table', function(){
            table = layui.table;
            table.render({
                id: 'check_user_table',
                elem: '#check_user_table',
                height: 330,
                url: '/user_group/table_list/' + groupId,
                method: 'post',
                size: 'sm',
                limits:[10,20,40,100],
                request: {
                    pageName: 'page',
                    limitName: 'size'
                },
                response: {
                    statusName: 'status', //规定数据状态的字段名称，默认：code
                    statusCode: 200, //规定成功的状态码，默认：0
                    msgName: 'msg', //规定状态信息的字段名称，默认：msg
                    countName: 'total', //规定数据总数的字段名称，默认：count
                    dataName: 'rows' //规定数据列表的字段名称，默认：data
                },
                page: true,
                cols: [[ //表头
                    {field: 'memberName', title: '用户名', width:120, sort: true, fixed: 'left'},
                    {field: 'name', title: '姓名', width:80, sort: true, fixed: 'left'},
                    {field: 'memberCardNum', title: '卡号', sort: true, width:100,fixed:'left'},
                    {field: 'phone', title: '手机号', width:110, sort: true,fixed:'left'},
                    {field: 'integral', title: '积分', width:80},
                    {field: 'createTime', title: '创建时间', sort: true,width: 150},
                    {field: 'birthday', title: '生日', sort: true,width: 100},
                    {field: 'gender', templet:function (e) {return e.gender==0?'男':'女'},title: '性别', width: 60}
                ]],
                done: function(res, curr){
                    page = curr;
                    size = res.size;
                    currentData = [];
                    for(let i=0;i< res.rows.length;i++){
                        currentData.push(res.rows[i].id);
                    }
                }
            });
        });
    }


    $("#page_size_selector").change(function () {
        let fromDate = $("#start_date").val();
        let toDate = $("#end_date").val();
        let selected = $(this).val();
        window.location.href = initUrl(0,selected,'',fromDate,toDate);
    })
    $("#search_bar").keydown(function (e) {
        let fromDate = $("#start_date").val();
        let toDate = $("#end_date").val();
        if (e.keyCode == 13) {
            let size = [[${pageObj.pageSize}]];
            let keyword = $(this).val();
            window.location.href = initUrl(0,size,keyword,fromDate,toDate);
        }
    })

    $("#search-btn").click(function () {
        let fromDate = $("#start_date").val();
        let toDate = $("#end_date").val();
        let size = [[${pageObj.pageSize}]];
        let keyword = $("#search_bar").val();
        window.location.href = initUrl(0,size,keyword,fromDate,toDate);
    })

    function initUrl(page,size,key,fromDate,toDate) {
        if (null == page) {
            page = 0;
        }
        return "/user_group/list?page="+ page +"&pageSize=" + size + "&keyword=" + key + "&fromDate=" + fromDate + "&toDate=" + toDate
    }

    function loadHref(id) {
        let groupId = id;
        $.ajax({
            url: '/user_group/table_list/' + groupId,
            type: 'post',
            // contentType: 'application/json; charset=UTF-8',
            success: function (res) {
                if (res.status == 200) {
                    window.location.href = '/user_group/export_user_group_record?groupId=' + groupId
                } else {
                    layer.msg("暂无数据，不支持导出",{time: 500})
                }
            }
        });

    }

    function buttonClickable() {
        setTimeout('resizeWindow()', 200);
    }
    function resizeWindow() {
        $(window).resize();
    }

</script>
</body>
<script src="/layui/layui.js"></script>
</html>